//
//  XCLoginController.swift
//  XCMicroBo
//
//  Created by 1 on 16/3/7.
//  Copyright © 2016年 1. All rights reserved.
//

import UIKit
import AFNetworking
import SVProgressHUD

class XCLoginController: UIViewController , UIWebViewDelegate{
    
    
    var myWebView = UIWebView(frame: UIScreen.mainScreen().bounds)
    

    

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        view = myWebView
        
        view.backgroundColor = UIColor.whiteColor()
        
        addLeftAndRightButton()
        
        //设置代理
        myWebView.delegate = self
        
        dataTask()
    }
    
    
    //发送登录请求
    func dataTask(){
        
//        let manager = AFHTTPSessionManager()
        
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=\(client_id)"  + "&redirect_uri=\(redirect_uri)"
        
        let url = NSURL(string: urlString)
        
        let request = NSURLRequest(URL: url!)
        
        myWebView.loadRequest(request)
        
    }
    
    //从网络获取数据
    
    //设置navigation的左右两个按钮
    func addLeftAndRightButton() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "测试账号", style: .Plain, target: self, action: "test")
    }
    
    func close(){
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    func test(){
    
        //需要在webView中 设置账号和密码
        let jsString = "document.getElementById('userId').value = 'leiggee@126.com', document.getElementById('passwd').value = 'oyonomg' "
        //通过字符串来执行javascrip 代码
        myWebView.stringByEvaluatingJavaScriptFromString(jsString)

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    //MARK:实现webView代理方法
    
    //开始加载数据
    func webViewDidStartLoad(webView: UIWebView) {
        
//        SVProgressHUD.show()
        SVProgressHUD.showWithStatus("正在加载  请稍后")
    }
    
    //数据加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        
        SVProgressHUD.dismiss()
    }
//    
//    //数据加载出错
//    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
//        
//    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        guard let urlString = request.URL?.absoluteString else{
            
            return false
        }
        
        if urlString.containsString("code"){
        
            guard let query = request.URL?.query else{
                
                return false
            }
            
            let codeStr = "code="
            //获取需要的code值
            let code = (query as NSString).substringFromIndex(codeStr.characters.count)
            
            UserCount.shareAcount.loadAccessToken(code, finished: { (isSuccess) -> () in
                
                
                if !isSuccess {
                    
                    SVProgressHUD.showErrorWithStatus("没网")
                    

                    
                    return
                }
                

                //登录成功  销毁当前界面
                SVProgressHUD.dismiss()
                
                //跳转页面
                NSNotificationCenter.defaultCenter().postNotificationName(swiftController, object: "oathur")

                self.close()
                

            })
            
            return false
        }
        
        return true
    }
    
    //获取accessToken
    
    
}
